﻿using System;
using System.Windows.Forms;
using SpeechLib;

namespace graduation_project.Voice_Recognition
{
    class ComSet
    {
            private static ComSet com = null;
            //private SpSharedRecognizer shareRecognizer = new SpSharedRecognizer();    //共享性识别器
            private SpeechLib.SpSharedRecoContext shareRecoContext = null;   //共享识别器语境
            public ISpeechRecoGrammar shareRecoGrammar = null;       //共享识别器语法
            private System.Windows.Forms.Control TextBox;
            private string cmdXml = "E://WorkSpace//c++//graduation project//graduation project//Xml//XMLFile1.xml";
            //语法识别初始化
            public void ComSetInitialize()
            {
                try
                {
                    shareRecoContext = new SpSharedRecoContext();
                    //shareRecoContext = (SpSharedRecoContext)shareRecognizer.CreateRecoContext();
                    shareRecoGrammar = shareRecoContext.CreateGrammar(1);     //为识别的语句创建语法器
                    shareRecoGrammar.CmdLoadFromFile(cmdXml, SpeechLoadOption.SLOStatic);
                    //shareRecoContext.EventInterests = SpeechRecoEvents.SREAllEvents;
                    shareRecoContext.Recognition += new _ISpeechRecoContextEvents_RecognitionEventHandler(TextRecognize);   //为上下文添加处理的函数
                   // shareRecoGrammar.CmdSetRuleState(shareRecoGrammar.Rules.Item(0).Name,SpeechRuleState.SGDSInactive);
                  }
                catch (Exception er)
                {
                    MessageBox.Show("An  Error  Occured!", "Speech", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            //将识别的语句加载到文本框内
            public void TextRecognize(int Index, object obj, SpeechLib.SpeechRecognitionType type, SpeechLib.ISpeechRecoResult result)
            {
                TextBox.Text += result.PhraseInfo.GetText(0, -1, true);
            }
             //语音识别开始
            public void BeginRec(Control tbResult)
            {
                //shareRecoGrammar.CmdSetRuleState(shareRecoGrammar.Rules.Item(0).Name, SpeechRuleState.SGDSActive);
                shareRecoGrammar.DictationSetState(SpeechRuleState.SGDSActive);
                TextBox = tbResult;
            }
            public void closeRec()
            {
                shareRecoGrammar.DictationSetState(SpeechRuleState.SGDSInactive); 
            }
             //单实例
            public static ComSet instance()
            {
                if (com == null)
                    com = new ComSet();
                return com;
            }
    }
}
